var $ = jQuery.noConflict();
jQuery(function () {
    let translate_these = [
        __p("select your form"),
        __p("please select field"),
        __p("Please select your value"),
        __p("limitation is"),
        __p('submit'),
        __p('add new item'),
    ];
    get_translated_text(translate_these);
    // let value_limit_added = false;

});

function get_translated_text(text_dict) {
    jQuery.ajax({
        type: "POST",
        // async: false,
        url: ajaxurl,
        data: {
            action: 'translate',
            textdict: text_dict,
        },
        complete: function (data) {
            window.translates = data.responseJSON;
            selected_form_id();

            // console.log('translated data');
                // console.log(data);
                return data;
            },
    });
    // console.log("translate ajax msg");
    // console.log(msg);

}

function selected_form_id() {
    $('div.selections_container').remove();
    let value = $("#gf_ml_select_form").val();
    // console.log(value);
    let msg;
    $.ajax({
        type: "POST",
        url: ajaxurl,
        data: {action: 'formaction', formid: value},
        success: function (data) {
            window.fields_array = data;

            newfield(data);
            return data;
        },
    });
    // console.log('msg is:');
    // console.log(msg);
}

function __p(string) {
    return string;
}



function new_container(row) {
    return `
    <div class="selections_container" 
    id="selections_container_${row}" 
    >
            <div class="field_holder" id="field_holder_${row}" 
            style="float: ${window.translates.float};display: inline-block;">
            
            </div>
            <div class="value_holder" id="value_holder_${row}"
            style="float: ${window.translates.float};display: inline-block;">

            </div>

          
        </div>
    `
}
function newfield(data) {
    // console.log(data);
    let containers = $('div#all_containers div.selections_container');
    let row = containers.length;
    $('div#all_containers').append(new_container(row));
    let label = `<label for="field_holder_${row}">
                ${window.translates['please select field']}
                </label>`;
    let start_select = `<select class="field_holder" id="field_holder_${row}" onchange="newvalue(${row})">`;
    let opt=optionmaker(data);
    let end_select = `</select>`;
    // console.log(opt);
    field_div = `${label} ${start_select} ${opt} ${end_select}`;
    $(`div#field_holder_${row}`).append(field_div);
    newvalue(row)

}
function newvalue(row) {
    // console.log('row'+row);
    let form_id = $("#gf_ml_select_form").val();
    let field_id = $(`select#field_holder_${row}`).val();
    //console.log('field_id'+field_id)
    $.ajax({
        type: "POST",
        url: ajaxurl,
        data: {
            action: 'formaction',
            fieldid: field_id,
            formid: form_id
        },
        success: function (data) {
            let label = `<label for="value_holder_${row}">
                ${window.translates['Please select your value']}
                </label>`;
            let select_start = `<select class="value_holder" id="value_holder_${row}">`;
            let opt = optionmaker(data);
            let end_select = `</select>`;
            value_div = `${label} ${select_start} ${opt} ${end_select}`;
            $(`div#value_holder_${row}`).empty().append(value_div);
            // add_button(row);

        }
    })
    // if(row===0){add_value_limit()}
}
function add_button(row) {
    label = `<label for="add_new_button_holder_${row}"></label>`;
    img = `<img alt="${window.translates['add new item']}" src="${gf_ml_plugin.pluginurl}assets/img/pluss.svg" 
    id="btn_img_${row}" 
    class="btn_img" onclick="newfield(window.fields_array)"  />`;
    img_div = `${label} ${img}`;
    $(`div#add_new_button_holder_${row}`).empty().append(img_div);

}
function optionmaker(data) {
    //console.log(data);
    let opt='';
    for(let j=0;j<data.length;j++){
        arr=data[j];
        opt=opt+'\n'+`<option value="${arr['value']}">${arr['text']}</option>`;
    }


    return opt;

}
// function add_value_limit() {
//     // let btn_holder = $('#value_limit_btn');
//     // let value_input = $('#value_limit_input');
//     // let input_str = `<input type="number" size="4" id='limit_input_1'>`
//     // let btn_str = `<button id="submit_btn">${window.translates['submit']}</button>`
//     // btn_holder.empty().append(btn_str);
//     // value_input.empty().append(input_str);
//     $('#value_limit_holder').show();
// }

function get_limits() {
    jQuery('#submit_btn').hide();
    //console.log('we are in');
    const formid=jQuery('select#gf_ml_select_form').val();
    //console.log('formis'+formid);
    const all_options = jQuery('.selections_container').length;
    const limit_number = jQuery('#limit_input_1').val();
    let limits_array = {};
    limits_array['formid']=formid;
    limits_array['limit']=limit_number;
    limits_array['limits_on']=[];
    let field;
    let value;
    for (let j=0; j < all_options ; j++){
        fields={};
         field = $(`select#field_holder_${j}.field_holder`).val();
        if (typeof (field) === 'undefined'){continue;}
         value = $(`select#value_holder_${j}.value_holder`).val();
         fields['field']=field;
         fields['value']=value;
         limits_array['limits_on'].push(fields);

    }
    jQuery.ajax({
        url : ajaxurl,
        type : 'POST',
        data:{
            action:'sendingLimits',
            form_id:limits_array['formid'],
            limit_number:limits_array['limit'],
            limits_on:limits_array['limits_on']
        },
        success:function (data) {
            alert(data.msg);
            $('div.selections_container').remove();
        }

    } );
    // console.log(limits_array);

}